package cjm.task5.config;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;


@Configuration(proxyBeanMethods = false)
@RequiredArgsConstructor
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    final UserDetailsService userDetailsService;
    @Autowired
    private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;
    @Autowired
    private MyAuthenticationFailHandler myAuthenticationFailHandler;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/assets","/css","/js").permitAll()
                    .antMatchers("/usercon/**","/recordcon/**").hasRole("ADMIN")
                .antMatchers("/yqfk/**").hasRole("USER")
                //.antMatchers("/*").hasAnyRole("ADMIN", "USER")
                // 自定义登录界面
                .and().formLogin()
                    .loginPage("/login").permitAll()
                    .usernameParameter("userid")
                    .passwordParameter("userPassword")
                    .loginProcessingUrl("/doLogin")
                    // 设置成功后跳转的页面
                    .successHandler(myAuthenticationSuccessHandler)
                    .failureHandler(myAuthenticationFailHandler)
                    //.defaultSuccessUrl("/searchAllRecord")
                // 自定义退出登录请求Url、成功退出登录后的重定向Url
                .and().logout()
                    .invalidateHttpSession(true) //是否清除Http session中的内容
                    .logoutUrl("/outLogin").permitAll();
                    //.logoutSuccessUrl("/admin/login?logout");

        http.csrf().disable();
        http.headers().frameOptions().disable();
    }

}
